package com.qf.common.aop;

import com.qf.common.beans.ResultBean;
import com.qf.common.exceptions.CheckException;
import com.qf.common.exceptions.UnloginException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


/**
 * 处理和包装异常
 *
 * @time:2019年01月01日21:10:36
 */
@Slf4j
@Aspect
@Component
//@Order(-99)
public class ControllerAOP {

    @Pointcut("execution(public com.qf.common.beans.ResultBean *(..))")
    public void controllerMethod() {

    }

    @Around("controllerMethod()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        ResultBean<?> result;
        try {
            result = (ResultBean<?>) pjp.proceed();
        } catch (Throwable e) {
            result = handlerException(pjp, e);

        }
        return result;
    }

    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        ResultBean<?> result = new ResultBean();
        // 登陆异常 1
        if (e instanceof UnloginException) {
            result.setMsg("Unlogin");
            result.setCode(ResultBean.NO_LOGIN);
        }
//        // 没有权限 2
//        else if (e instanceof UnauthorizedException) {
//            result.setMsg("NO PERMISSION: " + e.getMessage());
//            result.setCode(ResultBean.NO_PERMISSION);
//        }

        // 已知异常 3
        else if (e instanceof CheckException) {
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.CHECK_FAIL);
        } else {
            log.error(pjp.getSignature() + " error ", e);
            e.printStackTrace();
            //TODO 未知的异常，应该格外注意，可以发送邮件通知等
            result.setMsg(e.toString());
            result.setCode(ResultBean.UNKNOWN_EXCEPTION);
        }

        return result;
    }
}
